package so.ifl.commons.tools.pinter.impl;

import java.io.ByteArrayOutputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.itextpdf.text.pdf.AcroFields;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;

import so.ifl.commons.tools.DateUtil;
import so.ifl.commons.tools.StringHelper;
import so.ifl.commons.tools.pinter.Iprinter;
import so.ifl.servcie.TransactionService;
import so.ifl.vo.TranRecordVo;

/**
 *create by aaron.lu
 *create at 2012-5-8 上午10:17:30
 *<mailto: atyuan.lu@gmail.com>
 **/
public class ReceiptPrinter implements Iprinter{
	
	Logger logger_ = LoggerFactory.getLogger(this.getClass());
	
	private String TRANSACTION_RECORD = "tran";

	@Override
	public void print(Map<String, Object> data, HttpServletResponse response,
			HttpServletRequest request) throws Exception {
		logger_.debug("param:" + data);
		
		TranRecordVo tranRecordVo = (TranRecordVo)data.get(TRANSACTION_RECORD);
		
		if (null == tranRecordVo) {
			throw new Exception("tranRecordVo is null...");
		}
		
		String servletPath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() +request.getContextPath();
		String model_path = servletPath + "/templates/Receipt.pdf";
		PdfReader reader = new PdfReader(model_path);
		
		BaseFont baseFontChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
		
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		
		PdfStamper pdfStamper = new PdfStamper(reader, baos);
		
		AcroFields form = pdfStamper.getAcroFields(); 
		form.addSubstitutionFont(baseFontChinese);
		
		form.setField("student_name_", tranRecordVo.getStudentName() + "(" + tranRecordVo.getStudentCertificateNumber() + ")");
		form.setField("office_name_", tranRecordVo.getOfficeName());
		form.setField("tranDate", null != tranRecordVo.getCreateTime()?DateUtil.YMD_SDF_POINT.format(tranRecordVo.getCreateTime()):"");
		
		form.setField("item0", tranRecordVo.getItemType() + "(当前缴费情况：应付￥" + tranRecordVo.getShouldPay() + ",已付￥" + (null != tranRecordVo.getPayEven()?tranRecordVo.getPayEven():tranRecordVo.getShouldPay()) + ")");
		form.setField("c0", "1");
		form.setField("m0", "￥" + tranRecordVo.getMoney());
		//form.setField("create_user_", tranRecordVo.getAccountOwner());  TODO
		form.setField("print_time_", "打印时间：" + DateUtil.YMD_SDF_POINT.format(new Date()));
		form.setField("tranCode", "NO:" + tranRecordVo.getTranCode());
		form.setField("create_user_", tranRecordVo.getCreateAccountOwner());
		
		pdfStamper.setFormFlattening(true); // 千万不漏了这句啊, */
		pdfStamper.close();

		ServletOutputStream out = response.getOutputStream();

		response.setContentType("application/pdf");
		logger_.info(baos.size() + " bytes has write to out..");

		baos.writeTo(out);
		out.flush();

		baos.close();
		out.close();
		
	}

	@Override
	public Map<String, Object> getData(HttpServletRequest request)
			throws Exception {
		ServletContext servletContext = request.getSession().getServletContext();		
		ApplicationContext appctx = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext);
		
		Map<String, Object> data = new HashMap<String, Object>();
		
		TransactionService transactionService = (TransactionService)appctx.getBean("transactionService");
		
		
		
		String tranCode = request.getParameter("tranCode");		
		
		Map<String, Object> params = new HashMap<String, Object>();		
		
		if (StringHelper.isNotEmpty(tranCode)) {
			params.put("tran_code_", tranCode);//使用时间截生成的序号查询
		 	
			List<TranRecordVo> list = transactionService.queryTranRecordAllInfo(params);//关联查询
			
			if (null != list && list.size() > 0) {
				data.put(TRANSACTION_RECORD, list.get(0));
 			}
			
				
		}
		return data;
	}

}
